<?php

namespace Admin\Frontend\Controllers;

use Complex\Exception;
use Helpers\Cache;
use Helpers\Tool;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\Assets;
use Admin\Models\sys\XhsysConfig;
use Helpers\XhException;
use Modules\Power;
use Services\ConfigManage;

class ConfigController extends ControllerBase
{

    /**
     * 配置列表页面
     *
     * create by ck 20161124
     */
    public function configListAction()
    {
        $this->view->pick('sys/configList');
        Assets::easyUI('js/sys/configList.js');
        $this->assets->addJs('assets/jquery/jquery.form.js');
        $listButtonArr = $listSearchArr = [];
        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'List_Search_status',
            'style' => 'width: 75px;',
            'data' => [2 => '--状态--',
                0 => '启动' ,
                1 => '禁用'
            ]
        ];
        $listSearchArr[] = ['type'=>'text', 'id'=>'List_Search_keyword', 'label'=>' 搜索：'];
        $listButtonArr[] = ['plain'=>'true' ,'id'=>'bt_list_add', 'text'=>'新增', 'icon'=>'fa-plus'];
        $listButtonArr[] = ['plain'=>'true' ,'id'=>'bt_list_enable', 'text'=>'启用', 'icon'=>'fa-chain'];
        $listButtonArr[] = ['plain'=>'true' ,'id'=>'bt_list_disable', 'text'=>'禁用', 'icon'=>'fa-chain-broken'];
        if (UserPower::checkUserPower('systemConfig_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        $this->view->setVars([
            'List'  => Template::createList('List', 'XHSys_Config', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取配置信息数据
     *
     * create by ck 20161124
     * modify by fyh 20181210
     */
    public function getConfigDataAction()
    {
        $type = $this->request->get('type');
        $keyword = $this->request->getPost('keyword', 'string');
        $status = $this->request->getPost('status', 'int');
        $search = [];
        if ($keyword) {
            $search['keyword'] = $keyword;
        }
        if ($status !=2) {
            $search['status'] = $status;
        }
        $this->view->disable();
        try {
            $result = ConfigManage::configDetConfigData($type, $search);
            return $result;
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改配置信息，并清除缓存
     *
     * create by ck 20161124
     * modify by fyh 20181210
     */
    public function modifyConfigAction()
    {
        $this->view->disable();
        $this->request->isPost() or die('（109117001）无数据！');
        $realData = Main::getRealData($this->request->getPost());
        if (!isset($realData['type']) || !in_array($realData['type'], ['HTTP', 'db', 'parameter'])) {
            throw new XhException('类型不存在');
        }
        try {
            ConfigManage::configModifyConfig($realData);
            return $this->sendSuccessResponse('操作成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 设置配置记录是否启用
     *
     * create by ck 20161124
     * modify by fyh 20181210
     */
    public function setConfigStateAction()
    {
        $this->view->disable();
        $target = $this->request->getPost('target', 'string');
        $type = $this->request->getPost('type', 'string');
        $ids    = $this->request->getPost('ids', 'string');
        $target && $ids or die('（109117003）无数据！');
        try {
            $config = new ConfigManage();
            $config->configSetConfigState($target, $ids, $type);
            return $this->sendSuccessResponse('操作成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除配置记录
     *
     * create by ck 20161124
     * modify by fyh 20181210
     */
    public function delConfigAction()
    {
        $this->view->disable();
        $ids    = $this->request->getPost('ids', 'string');
        $type    = $this->request->getPost('type', 'string');
        $ids or die('（109117003）无数据！');
        if (!$type) {
            throw new XhException('类型不存在');
        }
        try {
            $config = new ConfigManage();
            $config->configDelConfig($ids, $type);
            return $this->sendSuccessResponse('操作成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据名称获取配置信息
     *
     * @param string $configName
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170421
     */
    public function getConfigByNameAction($configName = '')
    {
        return $this->sendJsonResponse(Main::getConfigByName($configName, true));
    }


    /**
     * function explain
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180731
     */
    public function synCodeAction()
    {
        if (!Power::exist('synCode')) {
            return $this->sendViewError('缺少权限');
        }
        $synCode = Main::getConfigByName('synCode');
        if (!$synCode) {
            return $this->sendViewError('缺少配置');
        }
        $this->view->pick('sys/synCode');
        Assets::sweetAlert2('js/sys/synCode.js');
        unset($synCode['shellPath']);
        return $this->view->setVars([
            'items' => $synCode
        ]);
    }

    /**
     * 执行同步
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180731
     * modify by ck 20181031
     */
    public function doSynCodeAction()
    {
        $key = $this->request->getPost('key', 'string');
        if (!Power::exist('synCode') && $key != $this->config->get('key')) {
            return $this->sendErrorResponse(403, '缺少权限');
        }
        $code = $this->request->getPost('code', 'string');
        if (!$code) {
            return $this->sendErrorResponse(400, '缺少代码');
        }
        $synCode = Main::getConfigByName('synCode');
        if (!$synCode || !$synCode['shellPath'] || !array_key_exists($code, $synCode)) {
            return $this->sendErrorResponse(500, '缺少配置');
        }
        $shell = sprintf('%s %s 2>&1', $synCode['shellPath'], $code);
        exec($shell, $output, $returnVar);
        return $this->sendJsonResponse([
            'var' => $returnVar,
            'output' => implode('<br />', $output),
            'shell' => $shell
        ], true);
    }
}